﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using SalePartial.Utility;
using System.Collections;
using Telerik.Web.UI;
using System.Data;
using XunPan.Web.Globals;
using System.Collections.Specialized;
using SalePartial.BLL;
using SalePartial.Model;
using System.Data.SqlClient;

public partial class Trade_Resource_trade_retrieval : System.Web.UI.Page
{
    protected void Page_Load(object sender, System.EventArgs e)
    {
        if (!IsPostBack)
        {
            sdsEventsList.FilterParameters["Filter1"].DefaultValue = "";
            factor.Visible = false;
            rtbFilterName.Visible = false;
            LoadProvinces();
            rcSharedSubmitDate.RangeMaxDate = System.DateTime.Now;
            LoadAllLocationNodes(rtvLocation);
        }


    }



    //**************************************************************************************************************************8
    //该部分代码将加载省市联动下拉菜单
    //**************************************************************************************************************************8



    private void LoadProvinces()
    {
        rcbProvince.DataTextField = "ProvinceName";
        rcbProvince.DataValueField = "ID";
        rcbProvince.DataSource = xdsProvinces;
        rcbProvince.DataBind();
        rcbProvince.Items.Insert(0, new RadComboBoxItem("- 所有省份 -"));
    }

    private void LoadCites(string provinceID)
    {
        xdsCities.XPath = "/Cities/City[@PID='" + provinceID + "']";
        rcbCity.DataTextField = "CityName";
        rcbCity.DataValueField = "ID";
        rcbCity.DataSource = xdsCities;
        rcbCity.DataBind();
        rcbCity.Items.Insert(0, new RadComboBoxItem("- 所有城市 -"));
    }

    protected void rcbProvince_SelectedIndexChanged(object o, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (rcbProvince.SelectedIndex > 0)
        {
            LoadCites(e.Value);
        }
        else
        {
            rcbCity.Text = "";
        }
    }

    protected void rcbCity_SelectedIndexChanged(object o, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
    {

    }
    





    //**************************************************************************************************************************8
    //此部分代码将动态加载省市树状目录的加载
    //但由于集成了编辑功能，需要树状目录一次加载完毕，因此该部分代码没有启用
    //**************************************************************************************************************************8


    private static void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode)
    {
        DataSet data = new DataSet();
        data.ReadXml(HttpContext.Current.Server.MapPath("~/App_Data/XML/China_Provinces.xml"));


        foreach (DataRow row in data.Tables[0].Rows)
        {
            RadTreeNode node = new RadTreeNode();
            node.Text = row["ProvinceName"].ToString();
            node.Value = row["ID"].ToString();
            node.ExpandMode = expandMode;
            treeView.Nodes.Add(node);
        }

    }

    private static void LoadAllLocationNodes(RadTreeView treeView)
    {
        DataSet data = new DataSet();
        data.ReadXml(HttpContext.Current.Server.MapPath("~/App_Data/XML/China_Provinces.xml"));


        foreach (DataRow row in data.Tables[0].Rows)
        {
            RadTreeNode provincenode = new RadTreeNode();
            provincenode.Text = row["ProvinceName"].ToString();
            provincenode.Value = row["ID"].ToString();


            DataTable dt = GetCitiesData(provincenode.Value);

            foreach (DataRow dr in dt.Rows)
            {
                RadTreeNode citynode = new RadTreeNode();
                citynode.Text = dr["CityName"].ToString();
                citynode.Value = dr["ID"].ToString();
                provincenode.Nodes.Add(citynode);
            }

            treeView.Nodes.Add(provincenode);
        }


    }

    private static DataTable GetCitiesData(string pid)
    {
        DataSet data = new DataSet();
        data.ReadXml(HttpContext.Current.Server.MapPath("~/App_Data/XML/China_Cities.xml"));

        DataView dv = new DataView(data.Tables[0]);
        dv.RowFilter = "[PID] = '" + pid + "'";
        return dv.ToTable();

    }
    private static void PopulateNodeOnDemand(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
    {
        DataTable data = GetCitiesData(e.Node.Value);

        foreach (DataRow row in data.Rows)
        {
            RadTreeNode node = new RadTreeNode();
            node.Text = row["CityName"].ToString();
            node.Value = row["ID"].ToString();
            e.Node.Nodes.Add(node);
        }

        e.Node.Expanded = true;
    }

    protected void rtvLocation_NodeExpand(object sender, Telerik.Web.UI.RadTreeNodeEventArgs e)
    {
        PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSideCallBack);
    }



    //**************************************************************************************************************************8
    //下面代码断包括所有对filter的处理
    //
    //**************************************************************************************************************************8


    protected void btnNewFilter_Click(object sender, System.EventArgs e)
    {
        rdzFilterBuilder1.Visible = rdockFilterMenu.Visible;
        rdzFilterBuilder2.Visible = rdockFilterMenu.Visible;
        rdockFilterMenu.Visible = !rdockFilterMenu.Visible;

    }




  

    protected void btnApplyFilter_Click(object sender, System.EventArgs e)
    {
       

        if (rcbProvince.SelectedIndex > 0)
        {

            if (string.IsNullOrEmpty(sdsEventsList.FilterParameters["Filter1"].DefaultValue))
            {
                sdsEventsList.FilterParameters["Filter1"].DefaultValue = "[Province] = '" + rcbProvince.SelectedItem.Text + "'";
            }
            else
            {
                sdsEventsList.FilterParameters["Filter1"].DefaultValue += "AND [Province] = '" + rcbProvince.SelectedItem.Text + "'";
            }

        }
        if (tbKeyword.Text != "")
        {
            if (string.IsNullOrEmpty(sdsEventsList.FilterParameters["Filter1"].DefaultValue)) 
            {
                sdsEventsList.FilterParameters["Filter1"].DefaultValue = "([PartName] like '%" + tbKeyword.Text + "%' or [PartNumber] like '%" + tbKeyword.Text + "%' or [PartName] like '% " + tbKeyword.Text + "%')"; 
 
             } 
            else 
             {
                 sdsEventsList.FilterParameters["Filter1"].DefaultValue += " and ([PartName] like '%" + tbKeyword.Text + "%'or [PartNumber] like '%" + tbKeyword.Text + "%' or [PartName] like '% " + tbKeyword.Text + "%')"; 
            } 

     
        }

        if (rcbCity.SelectedIndex > 0)
        {
            if (string.IsNullOrEmpty(sdsEventsList.FilterParameters["Filter1"].DefaultValue))
            {
                sdsEventsList.FilterParameters["Filter1"].DefaultValue = "[City] = '" + rcbCity.SelectedItem.Text + "'";
            }
            else
            {
                sdsEventsList.FilterParameters["Filter1"].DefaultValue += "AND [City] = '" + rcbCity.SelectedItem.Text + "'";
            }
        }
        radGridMainlist.DataBind();
    }

    protected void btnRemoveFilter_Click(object sender, System.EventArgs e)
    {
        sdsEventsList.FilterParameters["Filter1"].DefaultValue = "";
        rcbProvince.Text = "";
        rcbProvince.ClearSelection();
        rcbCity.Text = "";
        rcbCity.Items.Clear();
        tbKeyword.Text = "";
        radGridMainlist.DataBind();

    }
    private string BuildFilterExpression()
    {
        StringCollection fe = new StringCollection();

        if (rntbMaxQuantity.Value != null)
        {
            fe.Add("[MaxQuantity] <=" + rntbMaxQuantity.Value.ToString());

        }

        if (rntbMinQuantity.Value != null)
        {
            fe.Add("[MaxQuantity] >=" + rntbMinQuantity.Value.ToString());

        }

        if (rdpFromSubmit.SelectedDate != null)
        {
            fe.Add("[AssignDate] >= '" + rdpFromSubmit.SelectedDate.Value.ToString("d") + "'");
        }

        if (rdpToSubmit.SelectedDate != null)
        {
            fe.Add("[AssignDate] <= '" + rdpToSubmit.SelectedDate.Value.ToString("d") + "'");
        }


        if (rtvLocation.CheckedNodes.Count > 0)
        {
            string provinceFilter = "";
            string cityFilter = "";

            foreach (RadTreeNode rtNode in rtvLocation.CheckedNodes)
            {
                switch (rtNode.Level)
                {
                    case 0:
                        provinceFilter = provinceFilter + rtNode.Text + "','";
                        break;
                    case 1:
                        cityFilter = cityFilter + rtNode.Text + "','";
                        break;
                    case 2:

                        break;
                    default:

                        break;
                }
            }

            if (provinceFilter.EndsWith(",'"))
            {
                provinceFilter = "[Province] IN ('" + provinceFilter.Remove(provinceFilter.LastIndexOf(",'")) + ")";
            }

            if (cityFilter.EndsWith(",'"))
            {
                cityFilter = "[City] IN ('" + cityFilter.Remove(cityFilter.LastIndexOf(",'")) + ")";
            }
            fe.Add(provinceFilter + " OR " + cityFilter);

        }

        //build warecube / process fields
        if (rtvCategoryTree.CheckedNodes.Count > 0)
        {
            string warecubeFilter = "";
            foreach (RadTreeNode rtNode in rtvCategoryTree.CheckedNodes)
            {
                if (!rtvCategoryTree.CheckedNodes.Contains(rtNode.ParentNode))
                {
                    warecubeFilter += string.Format("([Category] = '{0}') OR ", rtNode.Value);
                }
            }
            warecubeFilter = warecubeFilter.Remove(warecubeFilter.LastIndexOf(" OR "));

            fe.Add(warecubeFilter);
        }
        if (rtvProcessTree.CheckedNodes.Count > 0)
        {
            string processFilter = "";
            foreach (RadTreeNode rtNode in rtvProcessTree.CheckedNodes)
            {
                if (!rtvProcessTree.CheckedNodes.Contains(rtNode.ParentNode))
                {
                    processFilter += string.Format("([Category] = '{0}') OR ", rtNode.Value);
                }
            }
            processFilter = processFilter.Remove(processFilter.LastIndexOf(" OR "));

            fe.Add(processFilter);
        }



        if (fe.Count > 0)
        {
            string fullExpression = "(";
            for (int i = 0; i <= fe.Count - 1; i++)
            {
                fullExpression = fullExpression + fe[i] + ") AND (";
            }
            fullExpression = fullExpression.Remove(fullExpression.LastIndexOf(" AND ("));
            return fullExpression;

        }
        else
        {
            return "";
        }

    }

    private void ParseFilterExpression(string filter)
    {
        filter = filter.Trim();

        if (filter.StartsWith("("))
        {
            filter = filter.Substring(1);
        }
        if (filter.EndsWith(")"))
        {
            filter = filter.Remove(filter.Length - 1);
        }

        string[] separator = { ") AND (" };

        string[] sa = filter.Split(separator, StringSplitOptions.RemoveEmptyEntries);

        if (sa.Length > 0)
        {
            string r = "'";


            for (int i = 0; i <= sa.Length - 1; i++)
            {
                sa[i] = sa[i].Trim();
                if (sa[i].StartsWith("[MaxQuantity] <="))
                {
                    rntbMaxQuantity.Value = Convert.ToDouble(sa[i].Replace("[MaxQuantity] <=", ""));
                }
                if (sa[i].StartsWith("[MaxQuantity] >="))
                {
                    rntbMinQuantity.Value = Convert.ToDouble(sa[i].Replace("[MaxQuantity] >=", ""));
                }



                if (sa[i].StartsWith("[AssignDate] >= '"))
                {
                    rdpFromSubmit.SelectedDate = Convert.ToDateTime(sa[i].Replace("[AssignDate] >= ", "").Trim(r.ToCharArray()));
                }


                if (sa[i].StartsWith("[AssignDate] <= '"))
                {
                    rdpToSubmit.SelectedDate = Convert.ToDateTime(sa[i].Replace("[AssignDate] <= ", "").Trim(r.ToCharArray()));
                }

                if (sa[i].StartsWith("[Province] IN ("))
                {
                    string temp = sa[i].Replace("[Province] IN ('", "");
                    temp = temp.Remove(temp.Length - 2);
                    temp = temp.Replace("','", "|");
                    string[] provinces = temp.Split('|');

                    for (int k = 0; k <= provinces.Length - 1; k++)
                    {
                        RadTreeNode rtNode = rtvLocation.FindNodeByText(provinces[k]);
                        if (rtNode != null)
                        {
                            rtNode.Checked = true;
                        }
                    }

                }

                if (sa[i].StartsWith("[City] IN ("))
                {
                    string temp = sa[i].Replace("[City] IN ('", "");
                    temp = temp.Remove(temp.Length - 2);
                    temp = temp.Replace("','", "|");
                    string[] cities = temp.Split('|');

                    for (int k = 0; k <= cities.Length - 1; k++)
                    {
                        RadTreeNode rtNode = rtvLocation.FindNodeByText(cities[k]);
                        rtNode.Checked = true;
                    }

                }

                if (sa[i].StartsWith("([Product] LIKE"))
                {
                    rtvCategoryTree.DataBind();

                    string temp = sa[i].Replace("%')", "");
                    temp = temp.Replace("([Product] LIKE '%", "");
                    temp = temp.Replace(" OR ", "|");
                    string[] warecubes = temp.Split('|');

                    for (int k = 0; k <= warecubes.Length - 1; k++)
                    {
                        RadTreeNode rtNode = rtvCategoryTree.FindNodeByValue(warecubes[k]);
                        rtNode.Checked = true;
                    }
                }

                if (sa[i].StartsWith("([Technology] LIKE"))
                {
                    rtvProcessTree.DataBind();

                    string temp = sa[i].Replace("%')", "");
                    temp = temp.Replace("([Technology] LIKE '%", "");
                    temp = temp.Replace(" OR ", "|");
                    string[] process = temp.Split('|');

                    for (int k = 0; k <= process.Length - 1; k++)
                    {
                        RadTreeNode rtNode = rtvProcessTree.FindNodeByValue(process[k]);
                        rtNode.Checked = true;

                    }

                }

            }

        }



    }

    protected void btnClearFilter_Click(object sender, System.EventArgs e)
    {
        bool isEditMode = !rtbFilterName.Enabled;
        string p = rtbFilterName.Text;
        ResetFilterInputControls();
        if (isEditMode)
        {
            rtbFilterName.Enabled = isEditMode;
            rtbFilterName.Text = p;
        }

        sdsEventsList.FilterParameters["Filter1"].DefaultValue = "";
        rtvLocation.UncheckAllNodes();
        rtvLocation.UnselectAllNodes();
        rtvProcessTree.UncheckAllNodes();
        rtvProcessTree.UnselectAllNodes();
        rtvCategoryTree.UncheckAllNodes();
        rtvCategoryTree.UnselectAllNodes();
        radGridMainlist.DataBind();

    }

    protected void btnExeFilter_Click(object sender, System.EventArgs e)
    {
        sdsEventsList.FilterParameters["Filter1"].DefaultValue = BuildFilterExpression();
        radGridMainlist.DataBind();
    }

    protected void btnReturn_Click(object sender, System.EventArgs e)
    {
        ResetFilterInputControls();

        rdzFilterBuilder1.Visible = rdockFilterMenu.Visible;
        rdzFilterBuilder2.Visible = rdockFilterMenu.Visible;
        rdockFilterMenu.Visible = !rdockFilterMenu.Visible;
    }

    private void ResetFilterInputControls()
    {
        rtbFilterName.Enabled = true;
        rtbFilterName.Text = "";
        rdpFromSubmit.Clear();
        rdpToSubmit.Clear();
        rntbMaxQuantity.Text = "";
        rntbMinQuantity.Text = "";
        rtvLocation.UncheckAllNodes();
        rtvLocation.UnselectAllNodes();
    }


    protected void rtvCategoryTree_DataBound(object sender, System.EventArgs e)
    {
    }

    protected void radGridMainlist_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {

        switch (e.CommandName.ToLower())
        {

            case "viewdetails":
                string InquiryID = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["InquiryID"].ToString();
                HttpContext.Current.Session["InquiryID"] = InquiryID;
                Response.Redirect(e.CommandArgument.ToString(), false);
                break;
        }
    }

}